package timer

import (
	"fmt"
	"gogame/gameconfig"
	"gogame/gameservice"
	"gogame/gameservice/gateway"
	"gogame/gameservice/service"
	"gogame/lib/timer"
	"gogame/logger"
	"sync"
)

type Service struct {
	service.Service
	stopMu    sync.Mutex
	isStop    bool                // 是否接受外部stop
	TimerType string              // 定时器类型 本服还是跨服
	Timer     *timer.ManageStruct // 定时器实现
	RpcManage *gateway.RpcManage  // rpc管理 主要用于和worker通讯

}

func NewService() service.IService {
	_service := &Service{
		TimerType: GetTimerType(),
		Timer:     timer.NewTimer(),
	}

	_service.RpcManage = gateway.NewRpcManage(_service)

	// 这里设置tag主要是在定时服务启动时区别定时器类型
	_service.SetTag(_service.TimerType)

	return _service
}

func init() {
	gameservice.Service2NewFunc["timer"] = NewService
}

// GetTimerType 获取定时器类型
func GetTimerType() string {
	_timerType := "timer"
	_gameVer := gameconfig.ServerConfig.GetGameVer()
	// 跨服定时器
	if _gameVer == "cross" {
		_timerType = "crosstimer"
	}

	return _timerType
}

// StartServer 开始服务
func (s *Service) StartServer(serviceName, listen string) {
	// 初始化日志
	logger.InitLog("timer", serviceName)
	// rpcManage开启
	s.RpcManage.Run(serviceName, fmt.Sprintf("%s:-1", s.TimerType))
	// 启动定时器
	s.Timer.Run(s.TimerType)
}

// StopServer 停止服务
func (s *Service) StopServer() {
	s.stopMu.Lock()
	defer s.stopMu.Unlock()

	if s.isStop {
		return
	}

	s.isStop = true
	s.Timer.Stop()
	s.RpcManage.Stop()
}

// HandleNotice 处理服务通知
func (s *Service) HandleNotice(data []any) {
}
